﻿using GCC.Container.Abstracts;
using GCC.Container.Models;
using GCC.APIContainer.Utilities;
using Microsoft.AspNetCore.Mvc;

using tcm.entity;
using tcm.request;
using tcm.response;
using tcm.utils;
using Microsoft.AspNetCore.Http;

namespace tcm.Controller
{
    [ApiController]
    [Route("tcm/user")]
    public class UserController : GCCAPIControllerBase
    {
        public UserController(AbsGCCContext context) : base(context)
        {

        }

        [HttpGet("query")]
        public DataResponse<List<User>> queryUser([FromQuery] UserQueryRequest userRequest)
        {

            var dbres = GCCEntrance.DBManager.GlobalDB.Select<User>()
                .WhereIf(userRequest.id != null, a => a.id == userRequest.id)
                .WhereIf(!string.IsNullOrEmpty(userRequest.uname), a => a.uname.Contains(userRequest.uname))
                .WhereIf(userRequest.bind_wx != null, a=>a.bind_wx == userRequest.bind_wx)
                .WhereIf(!string.IsNullOrEmpty(userRequest.id_card), a=>a.id_card == userRequest.id_card)
                .WhereIf(userRequest.beginTime != null, a=>a.create_date >= userRequest.beginTime)
                .WhereIf(userRequest.endTime != null, a=> a.create_date <= userRequest.endTime)
                .WhereIf(userRequest.sex != null, a=> a.sex == userRequest.sex)
                .WhereIf(!string.IsNullOrEmpty(userRequest.login_name), a=>a.login_name.Contains(userRequest.login_name))
                .WhereIf(userRequest.is_line != null, a => a.is_line == userRequest.is_line)
                .WhereIf(!string.IsNullOrEmpty(userRequest.wx_id), a => a.wx_id == userRequest.wx_id)
                .WhereIf(userRequest.type != null, a => a.type == userRequest.type)
                .Where(a => a.status == 1).OrderByDescending(a => a.create_date)
                .Count(out var count)
                .Page(userRequest.PageIndex ?? 1, userRequest.PageSize)
                .ToList();

            return HandleData(dbres, count);

        }

        [HttpPost("add")]
        public Result addUser(UserRequest userRequest) 
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;

            // 查询微信id是否存在
            List<User> list = GCCEntrance.DBManager.GlobalDB.Select<User>().Where(a => a.wx_id == userRequest.wx_id).ToList();
            if (list != null && list.Count > 0)
            {
                // 更新用户信息
                userRequest.id = list.First().id;
                try
                {
                    UpdateUserReq req = new UpdateUserReq();
                    update(userRequest, req);
                    result.msg = "数据库中已存在用户信息，用户信息已更新！";
                }
                catch (Exception e)
                {
                    result.code = 1;
                    result.msg = e.Message;
                }
                
                return result;
            }

            // mac地址存在，更新之前该mac地址有的数据为空
            if (!String.IsNullOrEmpty(userRequest.tmp_mac))
            {
                int mm = GCCEntrance.DBManager.GlobalDB.Update<User>().Set(a => a.tmp_mac == null).Where(a => a.tmp_mac == userRequest.tmp_mac).ExecuteAffrows();
                //Logger.Information(String.Format("更新mac，Num:{}", mm));
            }

            long userId = IdUtils.getId();
            User user = BeanUtils.copy<User, UserRequest>(userRequest);
            user.status = 1;
            user.id = userId;
            user.create_by = userId;
            user.create_date = DateTime.Now.ToLocalTime();
            user.update_by = userId;
            user.update_date = DateTime.Now.ToLocalTime();

            // 设置有效
            user.status = 1;

            int m = GCCEntrance.DBManager.GlobalDB.Insert(user).ExecuteAffrows();
            if (m <= 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "入库失败！";
            }
            else 
            {
                result.id = userId;

                // 生成order信息
                //long orderId = setAddOrder(userId);
                //// 生成report信息
                //setReport(userId, orderId);
                
            }

            return result;
        }

        [HttpPut("update")]
        public UpdateUserReq updateUser(UserRequest userRequest)
        {
            UpdateUserReq result = new UpdateUserReq();
            result.code = GlobalConstant.Success;

            try
            {
                update(userRequest, result);

                long userId = (long)userRequest.id;
                
            }
            catch (Exception e)
            {
                result.code = GlobalConstant.Failure;
                result.msg = e.Message;
            }
           
            return result;
        }

        private void update(UserRequest userRequest, UpdateUserReq result)
        {
            if (userRequest.id == null) 
            {
                result.code = GlobalConstant.Failure;
                result.msg = "id为空！";
                return;
            }
            long userId = (long)userRequest.id;
            if (userId == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "id为空！";
                return;
            }

            List<User> list = GCCEntrance.DBManager.GlobalDB.Select<User>().Where(a => a.id == userId).ToList();
            if (list == null || list.Count == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "数据库中没有id:" + userId + "的数据！";
                return;
            }

            User user = list.First();
            BeanUtils.copy<User, UserRequest>(userRequest, ref user);
            user.update_by = userId;
            user.update_date = DateTime.Now.ToLocalTime();

            if (!String.IsNullOrEmpty(userRequest.tmp_mac))
            {
                int mm = GCCEntrance.DBManager.GlobalDB.Update<User>().Set(a =>a.tmp_mac == null).Where(a => a.tmp_mac == userRequest.tmp_mac).ExecuteAffrows();
                //Logger.Information(String.Format("更新mac，Num:{}", mm));
            }
            // 更新
            int m = GCCEntrance.DBManager.GlobalDB.Update<User>(userId).SetSource(user).ExecuteAffrows();

            if (m <= 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "更新失败！";
            }
            else
            {
                result.id = userId;
            }
        }

    }
}
